package com.fullstack.server.service

import cats.*
import cats.effect.Sync
import cats.implicits.*
import com.fullstack.common.domain.error.{ErrorInfo, RequestError, ServerError}
import com.fullstack.common.domain.user.{UpdateUserInfo, UserInfo}
import com.fullstack.server.core.Users
import com.fullstack.server.domain.user.User
import org.typelevel.log4cats.Logger
import com.fullstack.server.logging.syntax.*

import java.util.UUID

class UserService[F[_]: Sync: Logger](users: Users[F]):

  
  def addUser(userInfo: UserInfo): F[Either[ErrorInfo, UserInfo]] =
    for 
      id <- UUID.randomUUID().toString.pure[F]
      _ <- users.create(User(id, userInfo.name, userInfo.age))
      userInfo <- users.findByUserId(id).flatMap {
        case None => RequestError(s"用户${id}未找到").asLeft.pure[F]
        case Some(user) => UserInfo(user.id, user.name, user.age).asRight.pure[F]
      }
    yield
      userInfo
      
      

  // 查看用户信息
  def getUserInfo(userId: String): F[Either[ErrorInfo, UserInfo]] =
    users.findByUserId(userId).flatMap{
      case None => RequestError(s"用户${userId}未找到").asLeft.pure[F]
      case Some(user) => UserInfo(user.id, user.name, user.age).asRight.pure[F]
    }

  // 更改用户信息： 用户名，签名，头像，等等
  def updateUserInfo(info: UserInfo): F[Either[ErrorInfo, UserInfo]] =
    for
      user <- users.findByUserId(info.id)
      newUser <- 
        users
        .update(user.get.copy(name = info.name, age = info.age))
        .log(u => u.toString, t => t.toString)
    yield
      newUser.fold(ServerError("处理异常").asLeft)(u => UserInfo(u.id, u.name, u.age).asRight)


end UserService



object UserService:

  def apply[F[_]: Sync: Logger](users: Users[F]) =
    new UserService[F](users)

end UserService



